using System;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using SecuBat.AttackPlugin;
using SecuBat.Crawling;
using System.Configuration;
using System.Threading;
using System.Globalization;

namespace SecuBat.UI
{
	/// <summary>
	/// Summary description for AttackReportForm.
	/// </summary>
	public class AttackReportForm : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.ComboBox comboBoxRuns;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.Button buttonShowResponse;
		private int _selectedAttackId;
		private System.Windows.Forms.Label label3;
        private System.Windows.Forms.TextBox textBoxAnalysis;
        private DataGridView dataGridViewReport;
        private DataGridViewTextBoxColumn colId;
        private DataGridViewTextBoxColumn colPageUrl;
        private DataGridViewTextBoxColumn colCrawlTime;
        private DataGridViewTextBoxColumn colAction;
        private DataGridViewTextBoxColumn colMethod;
        private DataGridViewTextBoxColumn colParameters;
        private DataGridViewTextBoxColumn colValues;
        private DataGridViewTextBoxColumn colResponseCode;
        private DataGridViewTextBoxColumn colPlugin;
        private DataGridViewTextBoxColumn colAnalysisResult;
        private DataGridViewCheckBoxColumn colExistsExploitUrl;
        private TableLayoutPanel tableLayoutPanel1;
        private System.Windows.Forms.TextBox textBoxExploitUrl;
        private System.Windows.Forms.Label label4;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public AttackReportForm()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
			
			DataSet runs = AttackDbManager.GetAttackerRuns();
            runs.Tables[0].Locale = CultureInfo.CurrentUICulture;
            runs.Tables[0].Columns.Add("DisplayText", typeof(string), "Name + ' (' + BeginTime + ')'");
            comboBoxRuns.DataSource = runs.Tables[0];
			comboBoxRuns.DisplayMember = "DisplayText";
			comboBoxRuns.ValueMember = "ID";

			buttonShowResponse.Enabled = false;
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.label1 = new System.Windows.Forms.Label();
            this.comboBoxRuns = new System.Windows.Forms.ComboBox();
            this.label2 = new System.Windows.Forms.Label();
            this.buttonShowResponse = new System.Windows.Forms.Button();
            this.label3 = new System.Windows.Forms.Label();
            this.textBoxAnalysis = new System.Windows.Forms.TextBox();
            this.dataGridViewReport = new System.Windows.Forms.DataGridView();
            this.colId = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.colPageUrl = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.colCrawlTime = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.colAction = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.colMethod = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.colParameters = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.colValues = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.colResponseCode = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.colPlugin = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.colAnalysisResult = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.colExistsExploitUrl = new System.Windows.Forms.DataGridViewCheckBoxColumn();
            this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
            this.textBoxExploitUrl = new System.Windows.Forms.TextBox();
            this.label4 = new System.Windows.Forms.Label();
            ((System.ComponentModel.ISupportInitialize)(this.dataGridViewReport)).BeginInit();
            this.tableLayoutPanel1.SuspendLayout();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(8, 8);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(82, 23);
            this.label1.TabIndex = 4;
            this.label1.Text = "Attacking Run:";
            this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // comboBoxRuns
            // 
            this.comboBoxRuns.DisplayMember = "BeginTime";
            this.comboBoxRuns.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.comboBoxRuns.Location = new System.Drawing.Point(96, 10);
            this.comboBoxRuns.Name = "comboBoxRuns";
            this.comboBoxRuns.Size = new System.Drawing.Size(403, 21);
            this.comboBoxRuns.TabIndex = 3;
            this.comboBoxRuns.ValueMember = "ID";
            this.comboBoxRuns.SelectedIndexChanged += new System.EventHandler(this.comboBoxRuns_SelectedIndexChanged);
            // 
            // label2
            // 
            this.label2.Location = new System.Drawing.Point(8, 32);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(64, 23);
            this.label2.TabIndex = 5;
            this.label2.Text = "Attacks:";
            this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // buttonShowResponse
            // 
            this.buttonShowResponse.Location = new System.Drawing.Point(7, 131);
            this.buttonShowResponse.Name = "buttonShowResponse";
            this.buttonShowResponse.Size = new System.Drawing.Size(112, 23);
            this.buttonShowResponse.TabIndex = 9;
            this.buttonShowResponse.Text = "Show Response";
            this.buttonShowResponse.Click += new System.EventHandler(this.buttonShowResponse_Click);
            // 
            // label3
            // 
            this.label3.Location = new System.Drawing.Point(7, 4);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(83, 23);
            this.label3.TabIndex = 10;
            this.label3.Text = "Analysis Text:";
            this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // textBoxAnalysis
            // 
            this.textBoxAnalysis.Dock = System.Windows.Forms.DockStyle.Fill;
            this.textBoxAnalysis.Location = new System.Drawing.Point(7, 30);
            this.textBoxAnalysis.Multiline = true;
            this.textBoxAnalysis.Name = "textBoxAnalysis";
            this.textBoxAnalysis.Size = new System.Drawing.Size(587, 95);
            this.textBoxAnalysis.TabIndex = 11;
            // 
            // dataGridViewReport
            // 
            this.dataGridViewReport.AllowUserToAddRows = false;
            this.dataGridViewReport.AllowUserToDeleteRows = false;
            this.dataGridViewReport.AllowUserToResizeRows = false;
            this.dataGridViewReport.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
            this.dataGridViewReport.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridViewReport.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.colId,
            this.colPageUrl,
            this.colCrawlTime,
            this.colAction,
            this.colMethod,
            this.colParameters,
            this.colValues,
            this.colResponseCode,
            this.colPlugin,
            this.colAnalysisResult,
            this.colExistsExploitUrl});
            this.dataGridViewReport.Location = new System.Drawing.Point(8, 58);
            this.dataGridViewReport.MinimumSize = new System.Drawing.Size(968, 360);
            this.dataGridViewReport.MultiSelect = false;
            this.dataGridViewReport.Name = "dataGridViewReport";
            this.dataGridViewReport.ReadOnly = true;
            this.dataGridViewReport.RowHeadersVisible = false;
            this.dataGridViewReport.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.CellSelect;
            this.dataGridViewReport.Size = new System.Drawing.Size(968, 360);
            this.dataGridViewReport.TabIndex = 13;
            this.dataGridViewReport.SelectionChanged += new System.EventHandler(this.dataGridViewReport_SelectionChanged);
            // 
            // colId
            // 
            this.colId.DataPropertyName = "ID";
            this.colId.HeaderText = "ID";
            this.colId.Name = "colId";
            this.colId.ReadOnly = true;
            this.colId.Visible = false;
            // 
            // colPageUrl
            // 
            this.colPageUrl.DataPropertyName = "PageUrl";
            this.colPageUrl.FillWeight = 24F;
            this.colPageUrl.HeaderText = "Page URL";
            this.colPageUrl.Name = "colPageUrl";
            this.colPageUrl.ReadOnly = true;
            // 
            // colCrawlTime
            // 
            this.colCrawlTime.DataPropertyName = "CrawlTime";
            this.colCrawlTime.FillWeight = 10F;
            this.colCrawlTime.HeaderText = "Crawl Time";
            this.colCrawlTime.Name = "colCrawlTime";
            this.colCrawlTime.ReadOnly = true;
            // 
            // colAction
            // 
            this.colAction.DataPropertyName = "Action";
            this.colAction.FillWeight = 18F;
            this.colAction.HeaderText = "Action";
            this.colAction.Name = "colAction";
            this.colAction.ReadOnly = true;
            // 
            // colMethod
            // 
            this.colMethod.DataPropertyName = "Method";
            this.colMethod.FillWeight = 6F;
            this.colMethod.HeaderText = "Method";
            this.colMethod.Name = "colMethod";
            this.colMethod.ReadOnly = true;
            // 
            // colParameters
            // 
            this.colParameters.DataPropertyName = "ParameterNames";
            this.colParameters.FillWeight = 12F;
            this.colParameters.HeaderText = "Parameters";
            this.colParameters.Name = "colParameters";
            this.colParameters.ReadOnly = true;
            // 
            // colValues
            // 
            this.colValues.DataPropertyName = "ParameterValues";
            this.colValues.FillWeight = 12F;
            this.colValues.HeaderText = "Values";
            this.colValues.Name = "colValues";
            this.colValues.ReadOnly = true;
            // 
            // colResponseCode
            // 
            this.colResponseCode.DataPropertyName = "ResponseCode";
            this.colResponseCode.FillWeight = 4F;
            this.colResponseCode.HeaderText = "Response Code";
            this.colResponseCode.Name = "colResponseCode";
            this.colResponseCode.ReadOnly = true;
            // 
            // colPlugin
            // 
            this.colPlugin.DataPropertyName = "IDPlugin";
            this.colPlugin.FillWeight = 4F;
            this.colPlugin.HeaderText = "Plugin ID";
            this.colPlugin.Name = "colPlugin";
            this.colPlugin.ReadOnly = true;
            // 
            // colAnalysisResult
            // 
            this.colAnalysisResult.DataPropertyName = "AnalysisResult";
            this.colAnalysisResult.FillWeight = 6F;
            this.colAnalysisResult.HeaderText = "Analysis Result";
            this.colAnalysisResult.Name = "colAnalysisResult";
            this.colAnalysisResult.ReadOnly = true;
            // 
            // colExistsExploitUrl
            // 
            this.colExistsExploitUrl.DataPropertyName = "ExploitUrlExists";
            this.colExistsExploitUrl.FillWeight = 4F;
            this.colExistsExploitUrl.HeaderText = "Exploit URL";
            this.colExistsExploitUrl.Name = "colExistsExploitUrl";
            this.colExistsExploitUrl.ReadOnly = true;
            this.colExistsExploitUrl.Resizable = System.Windows.Forms.DataGridViewTriState.True;
            this.colExistsExploitUrl.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
            // 
            // tableLayoutPanel1
            // 
            this.tableLayoutPanel1.ColumnCount = 2;
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 60.84711F));
            this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 39.15289F));
            this.tableLayoutPanel1.Controls.Add(this.textBoxExploitUrl, 1, 1);
            this.tableLayoutPanel1.Controls.Add(this.label4, 1, 0);
            this.tableLayoutPanel1.Controls.Add(this.buttonShowResponse, 0, 2);
            this.tableLayoutPanel1.Controls.Add(this.textBoxAnalysis, 0, 1);
            this.tableLayoutPanel1.Controls.Add(this.label3, 0, 0);
            this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 429);
            this.tableLayoutPanel1.Name = "tableLayoutPanel1";
            this.tableLayoutPanel1.Padding = new System.Windows.Forms.Padding(4);
            this.tableLayoutPanel1.RowCount = 3;
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 18.46154F));
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 81.53846F));
            this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 28F));
            this.tableLayoutPanel1.Size = new System.Drawing.Size(984, 161);
            this.tableLayoutPanel1.TabIndex = 14;
            // 
            // textBoxExploitUrl
            // 
            this.textBoxExploitUrl.Dock = System.Windows.Forms.DockStyle.Fill;
            this.textBoxExploitUrl.Location = new System.Drawing.Point(600, 30);
            this.textBoxExploitUrl.Multiline = true;
            this.textBoxExploitUrl.Name = "textBoxExploitUrl";
            this.textBoxExploitUrl.Size = new System.Drawing.Size(377, 95);
            this.textBoxExploitUrl.TabIndex = 13;
            // 
            // label4
            // 
            this.label4.Location = new System.Drawing.Point(600, 4);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(83, 23);
            this.label4.TabIndex = 12;
            this.label4.Text = "Exploit Url:";
            this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
            // 
            // AttackReportForm
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(984, 590);
            this.Controls.Add(this.tableLayoutPanel1);
            this.Controls.Add(this.dataGridViewReport);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.comboBoxRuns);
            this.MinimumSize = new System.Drawing.Size(992, 624);
            this.Name = "AttackReportForm";
            this.Text = "SecuBat Attack Report";
            this.Resize += new System.EventHandler(this.AttackReportForm_Resize);
            ((System.ComponentModel.ISupportInitialize)(this.dataGridViewReport)).EndInit();
            this.tableLayoutPanel1.ResumeLayout(false);
            this.tableLayoutPanel1.PerformLayout();
            this.ResumeLayout(false);

		}

		#endregion

		private void buttonShowResponse_Click(object sender, System.EventArgs e)
		{
			DataSet attackSet = AttackDbManager.GetAttack(_selectedAttackId);
			String response = attackSet.Tables[0].Rows[0][7].ToString();
            String tempPath = ConfigurationManager.AppSettings["TempDir"];
            String tempFileName = Path.Combine(tempPath, "secubattemp.html");

            if (!Directory.Exists(tempPath))
                Directory.CreateDirectory(tempPath);

            if (File.Exists(tempFileName))
                File.Delete(tempFileName);

			using (FileStream fs = File.OpenWrite(tempFileName))
			{
				using (StreamWriter sw = new StreamWriter(fs))
				{
					sw.Write(response);
				}
			}

            Process.Start(tempFileName);

		}

		private void comboBoxRuns_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			int idRun = (int) comboBoxRuns.SelectedValue;
			if (idRun > 0)
			{
				DataSet attacks = AttackDbManager.GetAttackReport(idRun);
                DataTable table = attacks.Tables[0];
                table.PrimaryKey = new DataColumn[] { table.Columns["ID"] };
                table.Columns.Add("ExploitUrlExists", typeof(bool), "LEN(ExploitUrl) > 0");
                dataGridViewReport.AutoGenerateColumns = false;
                dataGridViewReport.DataSource = table;

                if (table.Rows.Count < 1)
                {
                    this.textBoxAnalysis.Text = "";
                    this.textBoxExploitUrl.Text = "";
                }
			}
		}


        private void dataGridViewReport_SelectionChanged(object sender, EventArgs e)
        {
            if (dataGridViewReport.SelectedCells.Count > 0)
            {
                _selectedAttackId = (int)dataGridViewReport.SelectedCells[0].OwningRow.Cells["colId"].Value;
                buttonShowResponse.Enabled = _selectedAttackId > 0;
                DataRow row = ((DataTable)dataGridViewReport.DataSource).Rows.Find(_selectedAttackId);
                textBoxAnalysis.Text = row["AnalysisText"].ToString();
                textBoxExploitUrl.Text = row["ExploitUrl"].ToString();
            }
        }

        private void AttackReportForm_Resize(object sender, EventArgs e)
        {
            int changeX = this.Width - this.MinimumSize.Width;
            int changeY = this.Height - this.MinimumSize.Height;

            this.dataGridViewReport.Width = this.dataGridViewReport.MinimumSize.Width + changeX;
            this.dataGridViewReport.Height = this.dataGridViewReport.MinimumSize.Height + changeY;

            this.tableLayoutPanel1.Location = new Point(this.tableLayoutPanel1.Location.X, this.Height - 200);
        }
	}
}
